<template>
  <div class="doc-container">
    <!-- 顶部导航栏 -->
    <div class="header">
      <DocumentHeader
        :current-space="documentStore.currentSpace"
        :current-doc="documentStore.currentDoc"
        :show-comment-panel="documentStore.showCommentPanel"
        :favorite-loading="documentStore.favoriteLoading"
        :is-admin="documentStore.isAdmin"
        @toggle-favorite="onToggleFavorite"
        @toggle-comment-panel="onToggleCommentPanel"
        @more-command="onMoreCommand"
      />
    </div>

    <!-- 主体内容 -->
    <div class="doc-body">
      <!-- 左侧目录树 -->
      <div class="sidebar">
        <DocumentSlider
          :current-space="documentStore.currentSpace"
          :doc-tree="documentStore.docTree"
          :current-doc-id="documentStore.currentDocId"
          :loading="documentStore.treeLoading"
          :is-admin="documentStore.isAdmin"
          @select-node="onNodeClick"
          @new-root="onNewRoot"
          @new-node="onNewNode"
          @rename-node="onRenameNode"
          @delete-node="onDeleteNode"
          @permission="onPermission"
        />
      </div>

      <!-- 中间文档内容 -->
      <div class="content">
        <DocumentContent :doc="documentStore.currentDoc" ref="docContentRef" />
      </div>

      <!-- 右侧目录栏 -->
      <div class="toc-sidebar" :class="{ show: documentStore.showToc }">
        <div class="toc-header"><h3>目录</h3></div>
        <div class="toc-container" v-if="documentStore.showToc">
          <div
            v-for="item in documentStore.tocItems"
            :key="item.id"
            class="toc-item"
            :class="{
              active: documentStore.activeTocId === item.id,
              [`toc-level-${item.level}`]: true
            }"
            @click="scrollToHeading(item.id)"
          >
            {{ item.text }}
          </div>
        </div>
        <div class="btn">
          <div @click="onToggleToc" class="toggle-toc">
            <el-icon class="toc-icon">
              <ArrowRight v-if="documentStore.showToc" />
              <ArrowLeft v-else />
            </el-icon>
          </div>
        </div>
      </div>

      <!-- 评论面板 -->
      <div class="comments-panel" :class="{ show: documentStore.showCommentPanel }">
        <CommentsPanel
          :visible="documentStore.showCommentPanel"
          :comments="documentStore.comments"
          :current-user-id="userStore.userInfo.FUserId"
          :comment-text="documentStore.commentText"
          :current-doc-id="documentStore.currentDocId"
          :comment-loading="documentStore.commentLoading"
          @update:comment-text="val => (documentStore.commentText = val)"
          @submit="onSubmitComment"
          @reply="onReplyComment"
          @delete="onDeleteComment"
        />
      </div>
    </div>

    <!-- 新建文件夹弹窗 -->
    <el-dialog title="新建文件夹" v-model="folderDialogVisible" width="400px">
      <el-form :model="folderForm" label-width="80px">
        <el-form-item label="文件夹名" required>
          <el-input v-model="folderForm.title" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="folderDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="onSaveFolder">确定</el-button>
      </template>
    </el-dialog>

    <!-- 重命名弹窗 -->
    <el-dialog :title="`重命名${renameForm.type === 'folder' ? '文件夹' : '文档'}`" v-model="renameDialogVisible" width="400px">
      <el-form :model="renameForm" label-width="80px">
        <el-form-item label="新名称" required>
          <el-input v-model="renameForm.title" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="renameDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="onConfirmRename">确定</el-button>
      </template>
    </el-dialog>
    <DocumentPermissionDialog ref="permissionDialogRef" />
  </div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted, nextTick } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { ArrowLeft, ArrowRight } from "@element-plus/icons-vue";

import DocumentHeader from "../components/DocumentHeader.vue";
import DocumentSlider from "../components/DocumentSlider.vue";
import DocumentContent from "../components/DocumentContent.vue";
import CommentsPanel from "../components/CommentsPanel.vue";
import DocumentPermissionDialog from "../components/DocumentPermissionDialog.vue";

import { useUserStore } from "@/stores/modules/user";
import { useDocumentStore } from "@/stores/modules/document";
import type { Doc } from "@/api/interface/doc";

const route = useRoute();
const router = useRouter();
const userStore = useUserStore();
const documentStore = useDocumentStore();

// DOM 引用
const permissionDialogRef = ref<InstanceType<typeof DocumentPermissionDialog> | null>(null);
const docContentRef = ref<InstanceType<typeof DocumentContent> | null>(null);

// 弹窗数据
const folderDialogVisible = ref(false);
const folderForm = ref<{ title: string; parentId?: string }>({ title: "", parentId: "" });
const renameDialogVisible = ref(false);
const renameForm = ref<{ id: string; title: string; type: Doc.DocType }>({ id: "", title: "", type: "doc" });

/** ===================== 生命周期 ===================== */
onMounted(async () => {
  // 初始化加载评论
  if (documentStore.currentDocId) {
    await documentStore.loadComments(documentStore.currentDocId);
  }
});

/** ===================== 事件方法 ===================== */

// 切换收藏
const onToggleFavorite = async (): Promise<void> => {
  await documentStore.toggleFavorite(userStore.userInfo.FUserId);
};

// 更多操作
const onMoreCommand = (command: string): void => {
  switch (command) {
    case "edit":
      // 打开新标签页
      router.push({
        name: "knowledgeEdit",
        query: {
          id: documentStore.currentDocId!,
          spaceId: documentStore.currentSpace.FId
        }
      });
      break;
    case "history":
      ElMessage.info("历史版本功能开发中");
      break;
    case "export":
      ElMessage.info("导出功能开发中");
      break;
    case "share":
      ElMessage.info("分享功能开发中");
      break;
  }
};

// 切换评论面板
const onToggleCommentPanel = (): void => {
  documentStore.showCommentPanel = !documentStore.showCommentPanel;
};

// 点击文档树节点
const onNodeClick = async (node: Doc.DocNode): Promise<void> => {
  if (node.FType === "doc") {
    documentStore.currentDocId = node.FId;
    router.replace({ query: { ...route.query, docId: node.FId } });
    await documentStore.loadComments(node.FId);
    // 切换文档时添加阅读记录
    await documentStore.addReadHistory(node.FId);
  }
};

// 新建根节点
const onNewRoot = ({ type }: { type: Doc.DocType }): void => {
  if (type === "folder") {
    folderForm.value = { title: "", parentId: "" };
    folderDialogVisible.value = true;
  } else {
    router.push({
      name: "knowledgeEdit",
      query: {
        spaceId: documentStore.currentSpace.FId
      }
    });
  }
};

// 新建子节点
const onNewNode = ({ parentId, type }: { parentId: string; type: Doc.DocType }): void => {
  if (type === "folder") {
    folderForm.value = { title: "", parentId };
    folderDialogVisible.value = true;
  } else {
    router.push({
      name: "knowledgeEdit",
      query: {
        parentId,
        spaceId: documentStore.currentSpace.FId
      }
    });
  }
};

// 重命名节点
const onRenameNode = (node: Doc.DocNode): void => {
  renameForm.value = { id: node.FId, title: node.FTitle, type: node.FType };
  renameDialogVisible.value = true;
};

// 删除节点
const onDeleteNode = async (node: Doc.DocNode): Promise<void> => {
  try {
    await ElMessageBox.confirm(`确定删除 "${node.FTitle}" 吗？`, "删除确认", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    });
    await documentStore.deleteDocNode(node.FId);
  } catch {
    // 用户取消删除
  }
};

// 权限设置方法
const onPermission = async (node: Doc.DocNode): Promise<void> => {
  permissionDialogRef.value?.open(node.FId, documentStore.currentSpace.FId, node.FParentId);
};

// 保存新文件夹
const onSaveFolder = async (): Promise<void> => {
  if (!folderForm.value.title.trim()) {
    ElMessage.warning("请输入文件夹名称");
    return;
  }
  await documentStore.addDocNode({
    FSpaceId: documentStore.currentSpace!.FId,
    FParentId: folderForm.value.parentId,
    FTitle: folderForm.value.title,
    FType: "folder",
    FContent: "",
    FAuthorId: userStore.userInfo.FUserId
  });
  folderDialogVisible.value = false;
};

// 确认重命名
const onConfirmRename = async (): Promise<void> => {
  if (!renameForm.value.title.trim()) {
    ElMessage.warning("请输入新名称");
    return;
  }
  await documentStore.updateDocNode({
    FId: renameForm.value.id,
    FTitle: renameForm.value.title,
    FContent: ""
  });
  renameDialogVisible.value = false;
};

// 提交评论
const onSubmitComment = async (): Promise<void> => {
  await documentStore.submitComment(userStore.userInfo.FUserId);
};

// 回复评论
const onReplyComment = (comment: any): void => {
  documentStore.commentText = `@${comment.FUsername || comment.FUserId} `;
  nextTick(() => {
    const textarea = document.querySelector(".comment-editor textarea") as HTMLTextAreaElement;
    if (textarea) textarea.focus();
  });
};

// 删除评论
const onDeleteComment = async (commentId: string): Promise<void> => {
  await documentStore.deleteComment(commentId);
};

// 点击目录滚动
const scrollToHeading = (id: string): void => {
  const heading = document.getElementById(id);
  if (heading) {
    heading.scrollIntoView({ behavior: "smooth" });
    documentStore.activeTocId = id;
  }
};

// 切换目录显示
const onToggleToc = (): void => {
  documentStore.showToc = !documentStore.showToc;
};

// 提取目录
const extractToc = (): void => {
  if (!docContentRef.value) return;
  const headings = docContentRef.value.$el.querySelectorAll("h1, h2, h3, h4, h5, h6");
  const toc = Array.from(headings).map((heading, index) => {
    const el = heading as HTMLElement;
    const id = `heading-${index}`;
    el.id = id;
    return { id, text: el.innerText, level: parseInt(el.tagName[1]) };
  });
  documentStore.setTocItems(toc);
};

// 监听滚动，激活目录项
const handleScroll = (): void => {
  const headings = docContentRef.value?.$el.querySelectorAll("h1, h2, h3, h4, h5, h6");
  const scrollTop = docContentRef.value?.$el.scrollTop || 0;
  if (!headings) return;
  for (const heading of Array.from(headings).reverse()) {
    const el = heading as HTMLElement;
    if (el.offsetTop <= scrollTop + 100) {
      documentStore.activeTocId = el.id;
      break;
    }
  }
};

// 监听文档变化，自动生成目录
watch(
  () => documentStore.currentDoc,
  async doc => {
    if (doc) {
      nextTick(() => {
        extractToc();
        docContentRef.value?.$el.addEventListener("scroll", handleScroll);
      });
    }
  },
  { immediate: true }
);

// 监听路由变化，加载对应文档
watch(
  () => route.query.docId,
  async docId => {
    if (docId && docId !== documentStore.currentDocId) {
      documentStore.currentDocId = docId as string;
      await documentStore.loadComments(docId as string);
      // 通过URL直接访问文档时也添加阅读记录
      await documentStore.addReadHistory(docId as string);
    }
  },
  { immediate: true }
);
</script>

<style scoped lang="scss">
@import "./detail";
</style>
